from app.spider.yushu_book import YuShuBook
from .base import db, Base
from sqlalchemy import func


class Wish(Base):
    ''' 用户和想要书籍关系表 '''
    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User') # 方便查询的关系属性
    isbn = db.Column(db.String(13))
    launched = db.Column(db.Boolean, default=False) # 是否赠送成功

    @classmethod
    def get_user_wishs(cls, uid):
        # 查询我想要的书籍
        return Wish.query.filter_by(uid=uid, launched=False).order_by(db.desc(Wish.create_time)).all()

    @classmethod
    def get_gift_counts(cls, isbn_list):
        from app.models.gift import Gift
        # 查询我想要的书籍,有多少人在赠送.
        gift_list = db.session.query(func.count(Gift.id), Gift.isbn).\
            filter(Gift.launched == False, Gift.status == 1, Gift.isbn.in_(isbn_list)).\
            group_by(Gift.isbn).all()

        gift_dict = [{'count':i[0], 'isbn':i[1]} for i in gift_list] # 构建字典返回数据.
        return gift_dict

    @property
    def book(self):
        # 拿到当前书籍的信息.
        yushu_book = YuShuBook()
        yushu_book.search_by_isbn(self.isbn)
        return yushu_book.first